package com.jt.common.filter;
//过滤链

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

//过滤器(特殊的拦截器)
interface Filter{
    Boolean invoke();
}
//控制器
interface Servlet{
    void dispatch();//请求分发
}
//过滤链
class FilterChain{
    private List<Filter> filters=new CopyOnWriteArrayList<>();;//过滤器（请求数据过滤）
    private Servlet servlet;//控制器（请求控制逻辑）
    public FilterChain(List<Filter> filters,Servlet servlet){
        this.filters.addAll(filters);
        this.servlet = servlet;
    }
    public void doFilter(){//执行过滤链
        for (int i=0;i<filters.size();i++){
            if (! filters.get(i).invoke()) return;
        }
        servlet.dispatch();//请求分发
    }
}
public class FilterChainTests {
    public static void main(String[] args) {
        Filter filter1 = new Filter() {
            @Override
            public Boolean invoke() {
                System.out.println("我是filter1");
                return true;
            }
        };
        Filter filter2 = new Filter() {
            @Override
            public Boolean invoke() {
                System.out.println("我是filter2");
                return true;
            }
        };
        List<Filter> filters = new ArrayList<>();
        filters.add(filter1);
        filters.add(filter2);

        Servlet servlet = new Servlet() {
            @Override
            public void dispatch() {
                System.out.println("servlet执行");
            }
        };
        FilterChain fc =new FilterChain(filters,servlet);
        fc.doFilter();
    }
}
